package control;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.bean.perfil;
import model.bean.usuario;
import model.dao.UsuarioDao;

/**
 * Servlet implementation class ServletAlterarDadosPessoais
 */
@WebServlet("/AlterarDadosPessoais")
public class ServletAlterarDadosPessoais extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletAlterarDadosPessoais() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UsuarioDao dao = new UsuarioDao();
		usuario obj = new usuario();
		perfil pf = new perfil();
		String id = request.getParameter("id");
		obj.setNome(request.getParameter("nome"));
		obj.setDataNascimento(new Date());
		obj.setCpf(request.getParameter("CPF"));
		obj.setEmail(request.getParameter("email"));
		obj.setTelefone(request.getParameter("telefone"));
		obj.setLogin(request.getParameter("login"));
		obj.setSenha(request.getParameter("senha"));
		pf.setId(Integer.parseInt(request.getParameter("perfil")));
		obj.setPerfil(pf);

		obj.setId(Integer.parseInt(id));
		dao.update(obj);
		HttpSession session = request.getSession();
		session.setAttribute("user", obj);

		String urlRetorno = request.getHeader("referer");
		urlRetorno = urlRetorno.replace("?", ";");
		String[] urls = urlRetorno.contains(";") ? urlRetorno.split(";") : null;
		if (urls != null && urls.length > 0) {
			response.sendRedirect(urls[0]
					+ "?content=12&filtro=Dados alterados com sucesso!");
		} else {
			response.sendRedirect(urlRetorno + "?content=12");
		}
	}

}
